package com.db.ionio.io;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class FileIOClient {

    private final String hostName;
    private final int port;
    private final String fileName;

    public FileIOClient(String hostName, int port, String fileName) {
        this.hostName = hostName;
        this.port = port;
        this.fileName = fileName;
    }

    public void start() {
        long start = System.nanoTime();
        run();
        long time = System.nanoTime() - start;
        System.out.println(time);
    }

    private void run() {
        try (Socket socket = new Socket(hostName, port);
             DataOutputStream output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
             BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             FileInputStream fileStream = new FileInputStream(new File(fileName));
        ) {
            long fileSize = new File(fileName).length();
            System.out.format("file size is %d%n", fileSize);
            output.writeLong(fileSize);
            output.flush();

            final int bufferSize = 32 * 1024;
            final byte[] buffer = new byte[bufferSize];
            int n;
            while ((n = fileStream.read(buffer)) != -1) {
                output.write(buffer, 0, n);
                output.flush();
            }

            System.out.println(input.readLine());

        } catch (UnknownHostException unknownHostException) {
            unknownHostException.printStackTrace();
            System.err.println("Connection to unknown host failed");
        } catch (IOException ioException) {
            ioException.printStackTrace();
            System.err.println(ioException.getMessage());
        } catch (NullPointerException nullPointerException) {
            nullPointerException.printStackTrace();
            System.err.println(nullPointerException.getMessage());
        }
    }
}